package org.techmore.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import org.techmore.R;
import org.techmore.biz.CouponListActivityDataHandler;
import org.techmore.biz.WelcomeActivityDataHandler;
import org.techmore.utils.DownloadHandler;
import org.techmore.utils.HandlerThreadUtils;
import org.techmore.utils.ImageDownloadHandler;
import org.techmore.utils.PropertiesUtil;
import org.techmore.vo.AllCouponSeriesVO;
import org.techmore.zxing.client.android.CaptureActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class CouponListActivity extends Activity {
	
	private Handler imageHandler = null;
	
	private Handler progressHandler = null;
	
	private PropertiesUtil propertiesUtil = null;
	
	/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setScreenOrientation();
        setContentView(R.layout.techmore_couponlist);
    }
    /**
     * 設置屏幕方向
     */
    private void setScreenOrientation(){
    	getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);		//豎屏
//    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);		//橫屏
    }
    
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	Intent intent = this.getIntent();
    	String seachDataUrl = intent.getStringExtra("seachDataUrl");
    	if(null != seachDataUrl){
    		List<AllCouponSeriesVO> list = intent.getParcelableArrayListExtra("seachData");
//    		System.out.println(list.size());
        	setContentScrollViewHeightDynamic(list);
    	}else{
    		List<AllCouponSeriesVO> list = CouponListActivityDataHandler.getInstance().getCouponList(this);
        	setContentScrollViewHeightDynamic(list);
    	}
    	
    	//更新列表
    	propertiesUtil = PropertiesUtil.getInstance();
        progressHandler = new Handler(HandlerThreadUtils.getHandlerThreadInstance().getLooper()){
 			public void handleMessage(android.os.Message msg) {
 				int signNum = Integer.valueOf(msg.obj.toString());
 				if(-1 == signNum){
 					//download complete
 					File xmlFile = new File(Environment.getDataDirectory()+propertiesUtil.getValue("qr_xml_file_cache")
 							+"/"+propertiesUtil.getValue("qr_servicelist_filename"));
 					WelcomeActivityDataHandler.getInstance().insertXmlToSqlite(xmlFile,CouponListActivity.this);
 					CouponListActivity.this.startActivity(new Intent(CouponListActivity.this, CouponListActivity.class));
 					CouponListActivity.this.finish();
 				}else if(-2 == signNum){
 					//download error
 				}else{
// 					System.out.println("signNum:"+signNum);
 				}
 			};
 		};
    	
    }
    /**
     * 設置內容區
     */
    private void setContentScrollViewHeightDynamic(List<AllCouponSeriesVO> list){
    	
    	LinearLayout linearLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.techmore_couponlist, null);
    	
        TableLayout contentTableLayout = (TableLayout) linearLayout.findViewById(R.id.contentTableLayout);
        ScrollView contentScrollView = (ScrollView) linearLayout.findViewById(R.id.contentScrollView);
        RelativeLayout titleRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.titleRelativeLayout);
        RelativeLayout footerRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.footerRelativeLayout);
        
        LayoutParams contentLayoutParams = contentScrollView.getLayoutParams();
        //獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer contentScrollViewHeight = displayMetrics.heightPixels;
        
        contentLayoutParams.height = contentScrollViewHeight - titleRelativeLayout.getLayoutParams().height - footerRelativeLayout.getLayoutParams().height - 30;
        
        contentScrollView.setLayoutParams(contentLayoutParams);
        contentTableLayout.removeAllViews();
        
        AllCouponSeriesVO allCouponSeriesVO = null;
        for (int i = 0; i < list.size(); i++) {
        	allCouponSeriesVO = list.get(i);
        	HashMap<String,String> dataMap = new HashMap<String,String>();
        	//couponSeriesNo varchar(24),store varchar(100),subject varchar(100),img48xUrl varchar(200)
        	dataMap.put("couponId",allCouponSeriesVO.getCouponSeriesNo());
        	dataMap.put("couponName", allCouponSeriesVO.getSubject());
        	dataMap.put("businessName", allCouponSeriesVO.getStore());
        	dataMap.put("img48xUrl", allCouponSeriesVO.getImg48xUrl());
        	
        	contentTableLayout.addView(createTableRow(i,dataMap));
        	contentTableLayout.addView(createTableRowLine());
		}
        
        
        //搜索
        Button couponSearch = (Button) linearLayout.findViewById(R.id.couponSearch);
        couponSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				CouponListActivity.this.startActivity(new Intent(CouponListActivity.this,CouponSearchActivity.class));
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			}
		});
        
        adapterFootButton(footerRelativeLayout);
        
        setReflushButton(linearLayout);
        
        setContentView(linearLayout);
        
    }
    
    
    private void setReflushButton(LinearLayout linearLayout){
    	ImageButton couponReflush = (ImageButton) linearLayout.findViewById(R.id.couponReflush);
    	couponReflush.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				progressHandler.post(new DownloadHandler(propertiesUtil.getValue("qr_servicelist_url"), 
						progressHandler, propertiesUtil.getValue("qr_servicelist_filename")));
			}
		});
    }
    
    private void adapterFootButton(RelativeLayout linearLayout){
    	
    	//獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer windowWidth = displayMetrics.widthPixels;
        
    	LinearLayout couponListButton = (LinearLayout) linearLayout.findViewById(R.id.couponListButton);
        LinearLayout nearCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.nearCouponListButton);
    	LinearLayout myCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.myCouponListButton);
    	LinearLayout couponScanner = (LinearLayout) linearLayout.findViewById(R.id.couponScanner);
    	
    	RelativeLayout.LayoutParams layoutParams = null;
    	
    	if(240<windowWidth){
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) nearCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		nearCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) myCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		myCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponScanner.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponScanner.setLayoutParams(layoutParams);
    	}
    	
    	nearCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponListActivity.this, CouponMapActivity.class);
				CouponListActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    	
    	couponScanner.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CouponListActivity.this);
				if(preferences.getBoolean("isLogin",false)){
					Intent intent = new Intent();
					intent.setClass(CouponListActivity.this, CaptureActivity.class);
					CouponListActivity.this.startActivity(intent);
					overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				}else{
					CouponListActivity.this.startActivity(new Intent(CouponListActivity.this,CouponLoginActivity.class));
					overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				}
				return false;
			}
		});
    	
    	myCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponListActivity.this, MyCouponListActivity.class);
				CouponListActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    }
    
    private void addGotoDetailButtonListener(ImageButton button,final String couponId,final String img48xUrl){
    	button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("couponId", couponId);
				intent.putExtra("img48xUrl", img48xUrl);
				intent.setClass(CouponListActivity.this, ConsultCouponDetailsActivity.class);
				CouponListActivity.this.startActivity(intent);
			}
		});
    }
    
    /**
     * 創建數據行
     * @param index
     * @return
     */
    @SuppressWarnings("rawtypes")
	private View createTableRow(Integer index,HashMap dataMap){
		final View rowView = LayoutInflater.from(this).inflate(R.layout.techmore_couponlist_content_tablerow,null);
		TableRow tableRow = (TableRow) rowView.findViewById(R.id.contentTableRow);
		View contentRelativeLayoutCenter = tableRow.findViewById(R.id.contentRelativeLayoutCenter);
		TextView couponNameTextView = (TextView)tableRow.findViewById(R.id.couponNameTextView);
		TextView businessNameTextView = (TextView)tableRow.findViewById(R.id.businessNameTextView);
		ImageButton contentImageButtonRight = (ImageButton)tableRow.findViewById(R.id.contentImageButtonRight);
		
		Animation anim = new AlphaAnimation(0.1f, 1.0f); 
        anim.setInterpolator(new AccelerateDecelerateInterpolator());   
        anim.setDuration(1500); 
        final ImageView contentImageViewLeft = (ImageView) tableRow.findViewById(R.id.contentImageViewLeft);
        contentImageViewLeft.setAnimation(anim);
		
		imageHandler = new Handler(Looper.myLooper()){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				Bitmap bitmap = (Bitmap) msg.obj;
				contentImageViewLeft.setImageBitmap(bitmap);
			}
		};
		
		String imageuri = String.valueOf(dataMap.get("img48xUrl"));
		
		imageHandler.postDelayed(new ImageDownloadHandler(imageuri, 
				imageHandler, imageuri.substring(imageuri.lastIndexOf("/"), imageuri.length())), 100);
		
//		//設置行數據
		couponNameTextView.setText(String.valueOf(dataMap.get("couponName")));
		businessNameTextView.setText(String.valueOf(dataMap.get("businessName")));
		
		//動態控制行寬
		DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer screenWidth = displayMetrics.widthPixels;
        
        LayoutParams contentRelativeLayoutCenterLayoutParams = contentRelativeLayoutCenter.getLayoutParams();
        contentRelativeLayoutCenterLayoutParams.width = screenWidth - 10 - 48 - 30 - 48 - 30;
        contentRelativeLayoutCenter.setLayoutParams(contentRelativeLayoutCenterLayoutParams);
		
        //設置行間隔色
		if(index % 2 == 0){
			tableRow.setBackgroundColor(Color.parseColor("#F2F2F2"));
		}
		
		addGotoDetailButtonListener(contentImageButtonRight,String.valueOf(dataMap.get("couponId")),String.valueOf(dataMap.get("img48xUrl")));	//為ImageButton添加事件
		
		return rowView;
	}
    
    /**
     * 創建行分割線
     * @return
     */
    private View createTableRowLine(){
    	ViewGroup.LayoutParams linePara = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
    	
    	TextView tvLine = new TextView(this);
    	tvLine.setLayoutParams(linePara);
    	tvLine.setHeight(1);
    	tvLine.setBackgroundColor(Color.GRAY);
    	
    	return tvLine;
    }

}
